'''
Description:  play tts
Version: V1.0
Author: zw_1520@163.com
Date: 2025-04-22 10:22:22
LastEditors: zw_1520@163.com
LastEditTime: 2025-04-26 08:20:33
All rights reserved.
'''

import base64
import json
import requests
import time
from datetime import datetime


def set_status(ip, status):
    """Sets interaction status"""
    # InteractionStatus definition
    # InteractionStatus_Ready = 0  # Ready
    # InteractionStatus_Talk  = 1  # Talk
    # InteractionStatus_Task  = 2  # Task

    # Constructs data
    data = {
        "status": status
    }
    # Sends post request
    session = requests.Session()
    response = session.post(
        url='http://'+ip+':59201/rpc/aimdk.protocol.InteractionStatusService/SetStatus',
        headers={'content-type': 'application/json'},
        data=json.dumps(data, ensure_ascii=False)
    )


def get_status(ip):
    """Gets interaction status"""
    # Sends post request.
    session = requests.Session()
    response = session.post(
        url='http://'+ip+':59201/rpc/aimdk.protocol.InteractionStatusService/GetStatus',
        headers={'content-type': 'application/json'},
        data=json.dumps({}))
    # Prints response
    # print(f"Response status: {response.status_code}")
    # print(f"Response header: {response.headers}")
    print(f"Response:", json.loads(response.text)["status"])
    return json.loads(response.text)["status"]


def get_task_status(ip):
    """Gets task status"""
    # Sends post request
    session = requests.Session()
    response = session.post(
        url='http://'+ip+':59201/rpc/aimdk.protocol.InteractionTaskService/GetInteractionTaskStatus',
        headers={'content-type': 'application/json'},
        data=json.dumps({}))
    # Prints log
    # print(f"[GetStatus 响应]")
    # print(f"Status code: {response.status_code}")
    # print(f"Response headers: {response.headers}")
    print(f"Response:", json.loads(response.text)["status"])
    # return json.loads(response.text)["status"]


def encoded_text(text):
    text = text
    encoded_bytes = base64.b64encode(text.encode('utf-8'))
    encoded_text = encoded_bytes.decode('utf-8')

    return encoded_text


def post_data(text, motion, face):
    data = {
        "task": {
            "task_name": "interaction_task",
            "interaction_list": [
                {
                    "text": encoded_text(text),
                    "motion_name": motion,  # Motion id
                    "face_expression": face  # Faces id
                }
            ],
            "task_type": 0
        }
    }
    return data


def tts_post(orin_ip, x86_ip, text, motion, face):
    # Sets status
    set_status(orin_ip, status="InteractionStatus_Talk")
    time.sleep(0.5)
    set_status(orin_ip, status="InteractionStatus_Ready")
    response = requests.post(
        url='http://'+orin_ip +
            ':59201/rpc/aimdk.protocol.InteractionTaskService/StartInteractionTask',
        headers={'content-type': 'application/json'},
        data=json.dumps(post_data(text, motion, face),
                        ensure_ascii=False)  # Closes ascii for chinese
    )
    return response


def play_tts(text):
    orin_ip = "127.0.0.1"
    x86_ip = "192.168.100.100"
    # text = "领导在后续的参观中还会有更深入的了"
    motionID = ""
    faceID = ""

    get_status(orin_ip)
    get_task_status(orin_ip)
    TTS_status = tts_post(orin_ip, x86_ip, text, motionID, faceID)


def play_tts_with_motion(text, motion_id):
    orin_ip = "127.0.0.1"
    x86_ip = "192.168.100.100"
    # text = "领导在后续的参观中还会有更深入的了"
    # motionID = ""
    faceID = ""

    get_status(orin_ip)
    get_task_status(orin_ip)
    TTS_status = tts_post(orin_ip, x86_ip, text, motion_id, faceID)


def init_tts():
    orin_ip = "127.0.0.1"

    # Sets status
    set_status(orin_ip, status="InteractionStatus_Talk")
    time.sleep(0.5)
    set_status(orin_ip, status="InteractionStatus_Ready")


if __name__ == "__main__":
    text = "耦合驱动是指当一个机构的关节数量大于自由度数量，并且其中一个关节的运动始终与相连关节的运动成正比时，称为耦合驱动"
    print(text)
    play_tts(text)
